import { useEffect, useState } from 'react';

import { readFileInfo } from './useInspectImage';

import { getPromptAndNegative } from '@/common/utils/getPromptAndNegative';

import { useAppDispatch, useAppSelector } from '@/store/hooks';
import { setUserImageInfoMap } from '@/store/user';

export async function getMetadata(imgUrl: string) {
  let metadata;
  try {
    const res = await fetch(imgUrl);
    const arrayBuffer = await res.arrayBuffer();
    const blob = new Blob([arrayBuffer], { type: 'image/*' });

    const imageInfo = await readFileInfo(blob);
    const metadataObjString = imageInfo.find(
      (i) => i.key === 'sd-metadata'
    ).value;

    metadata = JSON.parse(metadataObjString);
  } catch (e) {
    metadata = null;
    console.log(e);
  }

  return metadata;
}
const useParseWebImage = (imgUrl?: string) => {
  const dispatch = useAppDispatch();
  const [parseLoading, setParseLoading] = useState<boolean>(true);
  const [info, setInfo] = useState<any>(null);
  const { userImageInfoMap } = useAppSelector((state) => state.user);
  useEffect(() => {
    if (!imgUrl) {
      setInfo(null);
      setParseLoading(false);
    } else {
      (async () => {
        setParseLoading(true);
        if (userImageInfoMap[imgUrl]) {
          setInfo(userImageInfoMap[imgUrl]);
        } else {
          const metadata = await getMetadata(imgUrl);
          if (metadata) {
            const { image, model } = metadata;
            const [prompt, negativePrompt] = getPromptAndNegative(image.prompt);
            setInfo({ prompt, negativePrompt, image, model });
            dispatch(
              setUserImageInfoMap({
                key: imgUrl,
                value: { prompt, negativePrompt, image, model },
              })
            );
          } else {
            setInfo(null);
          }
        }
        setParseLoading(false);
      })();
    }
  }, [dispatch, imgUrl, userImageInfoMap]);

  return { parseLoading, info };
};

export default useParseWebImage;
